package news.client;

import news.client.richtext.RichTextToolbar1;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.http.client.URL;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONNumber;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONString;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

public class NewsWriter extends Composite {
	VerticalPanel vp = new VerticalPanel();
	VerticalPanel writepanel = new VerticalPanel();
	int query;
	Grid grid = new Grid(1, 5);
	public NewsWriter() {
		super();
	}

	public NewsWriter(int query) {
		super();
		this.query = query;
		initWidget(vp);
		vp.getElement().setId("editPanel");
		addButton(vp);
		initGrid();
		getArticlesMap();
	}

	private void addButton(final VerticalPanel vp) {
		final Button add = new Button("添加");
		add.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
					if(vp.getWidgetIndex(writepanel) == -1){
						getWritePanel(null);
						vp.add(writepanel);}
					if(writepanel.isVisible()==false){
						writepanel.setVisible(true);
					}
			}
		});
		vp.add(add);
	}

	private void initGrid() {
		grid.setHTML(0, 0, "动作");
		grid.setHTML(0, 1, "ID");
		grid.setHTML(0, 2, "类型");
		grid.setHTML(0, 3, "标题	");
		grid.setHTML(0, 4, "日期");
		grid.getElement().setId("listarticlegrid");
		vp.add(grid);
	}

	public void getArticlesMap() {
		String url = GWT.getModuleBaseURL() + URL.encode("getArticleService")
				+ URL.encode("?id=" + query);// "?id=0"
		RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);
		try {
			builder.sendRequest(null, new GetArticleRequestCallback(query));
		} catch (RequestException e) {
		}
	}

	private class GetArticleRequestCallback implements RequestCallback {
		int id;

		public GetArticleRequestCallback(int query) {
			super();
			id = query;
		}

		public void onError(Request request, Throwable exception) {
		}

		public void onResponseReceived(Request request, Response response) {
			if (200 == response.getStatusCode()) {
				String respText = response.getText();
				if (respText.equals("")){
					return;
				}
				JSONValue respValue = JSONParser.parseLenient(respText);
				JSONArray trArray = respValue.isArray();
				getListTable(trArray, id);
			}
		}
	}

	protected void getListTable(JSONArray trArray, final int id) {
		grid.resizeRows(1);
		vp.clear();
		addButton(vp);
		vp.add(grid);
//		JSONObject selectedJO = null;
		for (int i = 0; i < trArray.size(); i++) {
			final JSONObject jo = trArray.get(i).isObject();
			final int d = (int) jo.get("ID").isNumber().doubleValue();
			int j = i + 1;
			grid.insertRow(j);
			grid.setHTML(j, 0, "<a href=''>删除</a>");
			Anchor a = new Anchor(new Integer(d).toString());
			a.addClickHandler(new ClickHandler() {
				public void onClick(ClickEvent event) {
					if (jo != null) {
						getWritePanel(jo);
						vp.add(writepanel);
					}
				}
			});
			grid.setWidget(j, 1,a);
			int type=(int)jo.get("Type").isNumber().doubleValue();
			String typeStr = "";
			if(type == 1)typeStr = "方案";
			if(type == 2)typeStr = "资讯";
			if(type == 3)typeStr = "邮件";
			grid.setHTML(j, 2, typeStr);
			grid.setHTML(j, 3, jo.get("Header").isString().stringValue().toString());
			JSONObject updateTime = jo.get("UpdatedTime").isObject();
			int year = 1900+(int)updateTime.get("year").isNumber().doubleValue();
			int month = 1+(int)updateTime.get("month").isNumber().doubleValue();
			int date = (int)updateTime.get("date").isNumber().doubleValue();
			int hour = (int)updateTime.get("hours").isNumber().doubleValue();
			int minute = (int)updateTime.get("minutes").isNumber().doubleValue();
			int seconds = (int)updateTime.get("seconds").isNumber().doubleValue();
			String dateStr = year+"年"+month+"月"+date+"日 "+hour+"时"+minute+"分"+seconds+"秒";
			grid.setHTML(j, 4, dateStr);
		}
	}

	private void getWritePanel(final JSONObject jo) {
		Grid inputGrid = new Grid(3,2);
		inputGrid.getElement().setId("inputGrid");
//		HorizontalPanel typePanel = new HorizontalPanel();
//		HorizontalPanel headerPanel = new HorizontalPanel();
//		HorizontalPanel authorPanel = new HorizontalPanel();
//		typePanel.add(new Label("类型"));
		final ListBox typeBox = new ListBox();
		typeBox.addItem("方案");
		typeBox.addItem("资讯");
		typeBox.addItem("邮件");
		if (jo != null && jo.get("Title") != null) {
			typeBox.setItemSelected((int) jo.get("Type").isNumber().doubleValue(), true);
		}
//		typePanel.add(typeBox);
		inputGrid.setWidget(0, 0, new Label("类型"));
		inputGrid.setWidget(0, 1, typeBox);
		final TextBox header = new TextBox();
		if (jo != null && jo.get("Header") != null) {
			header.setValue(jo.get("Header").isString().stringValue());
		}
		inputGrid.setWidget(1, 0, new Label("标题"));
		inputGrid.setWidget(1, 1, header);
//		headerPanel.add(new Label("标题"));
//		headerPanel.add(header);
		final TextBox author = new TextBox();
		if (jo != null && jo.get("Author") != null) {
			author.setValue(jo.get("Author").isString().stringValue());
		}
		inputGrid.setWidget(2, 0, new Label("作者"));
		inputGrid.setWidget(2, 1, author);
//		authorPanel.add(new Label("作者"));
//		authorPanel.add(author);
		final RichTextToolbar1 rt = new RichTextToolbar1();
		if (jo != null && jo.get("Content") != null) {
			rt.getRichTextPanel().setHTML(jo.get("Content").isString().stringValue().toString());
		}
		writepanel.clear();
//		writepanel.add(typePanel);
//		writepanel.add(headerPanel);
		writepanel.add(inputGrid);
		writepanel.add(rt);
		int id = 0;
		if (jo != null && jo.get("ID") != null)
			id = (int) jo.get("ID").isNumber().doubleValue();
		final int j = id;
		Button save = new Button("保存");
		save.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				JSONObject inputs = new JSONObject();
				inputs.put("content", new JSONString(rt.getRichTextPanel().getHTML()));
				inputs.put("author",new JSONString(author.getValue()));
				inputs.put("header", new JSONString(header.getValue()));
				inputs.put("type", new JSONString(new Integer(typeBox.getSelectedIndex()+1).toString()));
				String saveMessage = FieldVerifier.hasContent(inputs) + FieldVerifier.hasHeader(inputs) + FieldVerifier.hasType(inputs);
				String parameter = (jo==null? "?act=add":"?act=update");
				if(jo != null)inputs.put("id", new JSONNumber((double)j));
				if (saveMessage.equals("")) {
					RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, GWT.getModuleBaseURL()	+ URL.encode("getArticleService"+parameter));
					try {

						builder.sendRequest(inputs.toString(), new GetArticleRequestCallback(0));
					} catch (RequestException e) {
					}
				} else {
					Window.alert(saveMessage);
				}
			}
		});
		Button cancel = new Button("取消");
		cancel.addClickHandler(new ClickHandler(){
			public void onClick(ClickEvent event) {
				if(vp.getWidgetIndex(writepanel)!=-1)vp.remove(writepanel);
			}});
		HorizontalPanel saveCancel = new HorizontalPanel();
		saveCancel.add(save);
		saveCancel.add(cancel);
		writepanel.getElement().setId("writepanel");
		writepanel.add(saveCancel);

	}
}
